export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

export const handleCode = (res: Object, msg = '') => {
  wx.showToast({
    title: res.code === 0 ? msg : (res.msg || '失败'),
    icon: res.code === 0 ? 'success' : 'error',
    duration: 1500
  })
}

export const handleErrCode = (msg = '失败', icon = 'none') => {
  wx.showToast({
    title: msg,
    icon: icon,
    duration: 1500
  })
}

export const calculateDaysAgo = (dateString: string) => {
  const now = new Date().getTime()
  const createTime = new Date(dateString).getTime()
  const diff = now - createTime
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  if (days === 0) {
    return '今天'
  } else {
    return days + '天前'
  }
}
/**
 * 防抖
 * @param fn 需要防抖的函数
 * @param t 时间
 */
export const debounce = (func, delay) => {
  let timer;
  return function (...args) {
    const context = this;

    clearTimeout(timer);

    timer = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

/**
 * 节流
 * @param fn 需要节流的函数
 * @param t 时间
 */
export const throttle = (ft, t) => {
  let flag = true
  const interval = t
  return function (this, ...args) {
    if (flag) {
      fn.apply(this, args)
      flag = false
      setTimeout(() => {
        flag = true
      }, interval)
    }
  }
}
/**
 * 获取麦克风权限
 */

export function getSettingRecord(options = { scope: 'scope.record', content: '请前往设置页打开麦克风' }) {
  var self = this;
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        let auth = res.authSetting[options.scope]
        console.warn('scope.record=', auth, typeof auth)
        if (auth === true) { // 用户已经同意授权
          resolve(true)
        }
        else if (auth === undefined) {// 首次发起授权
          wx.authorize({
            scope: options.scope,
            success() {
              resolve(true)
            },
            fail(res) {
            }
          })
        }
        else if (auth === false) { // 非首次发起授权，用户拒绝过 => 弹出提示对话框
          wx.showModal({
            title: '授权提示',
            content: options.content,
            success: (tipRes) => {
              if (tipRes.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting[options.scope]) {
                      resolve(true)
                    }
                    console.warn('settingRes', settingRes)
                  },
                })
              }
            }
          })
        }
      },
    })
  })
}

/**
 * 开始录音
 */
export function startVoiceRecord() {
  let recorderManager = wx.getRecorderManager()
  wxst = wx.connectSocket({ // 开启websocket连接
    url: apiUrl,
    method: 'GET',
    success: function (res) {
      recorderManager.start({})
    }
  });

}
/**
 * 结束录音返回音频
 */
export function stopVoiceRecord(callback) {
  let recorderManager = wx.getRecorderManager()
  recorderManager.stop()
  recorderManager.onStop((res) => {
    callback(res)
  })
}
// export function pauseVoiceRecord() {
// }

// export function resumeVoiceRecord() {
// }


// export function getAvailableAudioSources() {
// }